package com.lagou.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

/**
 * created by kirito at 2020/7/12
 */
@Component
@RefreshScope
public class LimitingFilter implements GlobalFilter, Ordered {

    @Value("${limits.lagou-service-user}")
    private int limits;

    private Cache<String, Integer> cache = CacheBuilder.newBuilder().expireAfterWrite(60, TimeUnit.SECONDS).build();

    /**
     * 限制单个客户端IP在最近X分钟内请求注册接口不不能超过Y次
     *
     * @param exchange ServerWebExchange
     * @param chain    GatewayFilterChain
     * @return Mono<Void>
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        // 非注册请求，直接放行
        if (!path.contains("register")) {
            return chain.filter(exchange);
        }
        String ip = request.getRemoteAddress().getHostString();
        // 获取缓存中对应ip的请求次数
        Integer count = cache.getIfPresent(ip);
        count = count == null ? 0 : count;
        if (0 != limits && count > limits) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("success", false);
            jsonObject.put("message", "您频繁进行注册，请求已被拒绝");
            DataBuffer wrap = response.bufferFactory().wrap(jsonObject.toJSONString().getBytes(Charset.forName("UTF-8")));
            return response.writeWith(Mono.just(wrap));
        } else {
            count++;
            cache.put(ip, count);
            return chain.filter(exchange);
        }
    }

    @Override
    public int getOrder() {
        return 11;
    }

}
